//
//  AY_AudioViewController.m
//  AiYue
//
//  Created by mac on 2023/11/13.
//

#import "AY_AudioViewController.h"
#import "AY_AudioProgressView.h"
#import "AY_AudioBookCell.h"
#import "BDSSpeechSynthesizer.h"
#import "AY_DirectoryPage.h"
#import "AY_BookDetailViewController.h"
#import "AY_AudioMuLuView.h"

@interface AY_AudioViewController ()<SXAudioProgressViewDelegate, UICollectionViewDelegate, UICollectionViewDataSource, BDSSpeechSynthesizerDelegate, SXAudioMuLuDelegate, AVSpeechSynthesizerDelegate>

@property (nonatomic, strong) UIVisualEffectView *effectView;
@property (strong,nonatomic) UIImageView *backImage;
@property (strong,nonatomic) UIImageView *bookImage;
@property (strong,nonatomic) UILabel *bookName;
@property (strong,nonatomic) UILabel *bookChapter;
@property (strong, nonatomic) AY_AudioProgressView *textSlider;
@property (strong, nonatomic) NSArray *toolArrays;
@property (strong, nonatomic) UIButton *speedBtn;
@property (strong, nonatomic) UIButton *yinSeBtn;
@property (strong,nonatomic) UICollectionView *collectionView;
@property (strong,nonatomic) NSMutableArray *dataSource;
@property (strong,nonatomic) NSString *currentPageContent;
@property (assign,nonatomic) NSInteger page;
@property (assign,nonatomic) NSInteger readPage;
@property (strong,nonatomic) NSArray *pages;
@property (strong,nonatomic) NSMutableArray *chapters;
@property (assign,nonatomic) NSInteger chapterIndex;
@property (strong,nonatomic) NSAttributedString *content;
@property (strong, nonatomic) NSArray *speedArray;
@property (strong, nonatomic) NSArray *yinseArray;
@property (nonatomic,strong) AY_AudioMuLuView *muluView;
@property (nonatomic, assign) long long timeNum;
@end

@implementation AY_AudioViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.gk_navigationBar.hidden = YES;
    self.isInit = NO;
    self.isQuit = NO;
    
    self.speedArray = @[@"1倍速", @"2倍速", @"3倍速", @"4倍速", @"5倍速"];
    self.yinseArray = @[@"普通女声", @"普通男声", @"特别男声", @"情感男声", @"情感儿童声"];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refresh) name:ZFREFRESH object:nil];
}

- (void)refresh {
    self.isQuit = YES;
}

- (void)loadData {
    [AYApiRequest getBookRecommendListWithArticleId:self.bookModel.bookId andLimit:@"8" Success:^(AY_AudioBookModel * _Nonnull pkg) {
        self.dataSource = [NSMutableArray arrayWithArray:pkg.data];
        [self.collectionView reloadData];
    } failure:^(int status, NSString * _Nonnull info) {
        ShowToast(@"亲，网络不顺畅哟~");
    }];
}

- (void)setContent:(NSAttributedString *)content andChapters:(NSMutableArray *)chapters andPage:(NSInteger)page andChapterIndex:(NSInteger)chapterIndex andPages:(NSArray *)pages andIsFanye:(BOOL)isfanye andChapterTitle:(nonnull NSString *)chapterTitle {
    _content = content;
    _currentPageContent = [self p_subGetCurPageContentWithContent:content page:page pages:pages].string;
    _chapters = chapters;
    _page = page;
    _chapterIndex = chapterIndex;
    _pages = [NSArray arrayWithArray:pages];
    self.bookChapter.text = chapterTitle;
    [self.textSlider changePlayProgress:(int)_page totalLength:(int)_pages.count];
    
    if (!self.isQuit) {
        if (self.isInit) {
            [AY_ReadBookTool getManager].delegate = self;
//            [self configureOnlineTTS];
            if (![AY_ReadBookTool getWorkStatus]) {
                [self splitTextWithString:self.currentPageContent];
            }
        }
        if (isfanye) {
            if ([AY_ReadBookTool getWorkStatus]) {
//                [AY_ReadBookTool stopSpeak];
                [AY_ReadBookTool getManager].delegate = nil;
                [AY_ReadBookTool stopSpeak];
                [self splitTextWithString:self.currentPageContent];
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(5.0 * NSEC_PER_SEC)), dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                    [AY_ReadBookTool getManager].delegate = self;
                });
            }
//            if ([BDSSpeechSynthesizer sharedInstance].synthesizerStatus == BDS_SYNTHESIZER_STATUS_PAUSED) {
//                [[BDSSpeechSynthesizer sharedInstance] pause];
//            }else {
//                [[BDSSpeechSynthesizer sharedInstance] cancel];
//                [self splitTextWithString:self.currentPageContent];
//            }
        }
    }
    self.isQuit = NO;
}

- (void)setIsInit:(BOOL)isInit {
    _isInit = isInit;
    if (self.isInit) {
        [self configureOnlineTTS];
    }
}

- (void)setIsQuit:(BOOL)isQuit {
    _isQuit = isQuit;
}

-(void)configureOnlineTTS{
//    [AYApiRequest APPConfigSuccess:^(AY_ConfigModel * _Nonnull pkg) {
//        if ([BDSSpeechSynthesizer sharedInstance].synthesizerStatus != BDS_SYNTHESIZER_STATUS_WORKING) {
//            [self configureOnlineTTSDataWithApiKey:pkg.data.BAIDU_TTS_API_Key andSecretKey:pkg.data.BAIDU_TTS_Secret_Key];
//        }
//    } failure:^(int status, NSString * _Nonnull info) {
//        ShowToast(@"亲，网络不顺畅哟~");
//    }];
}

- (void)configureOnlineTTSDataWithApiKey:(NSString *)apiKey andSecretKey:(NSString *)secretKey {
    [[BDSSpeechSynthesizer sharedInstance] setSynthesizerDelegate:self];
//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(speechEnd:) name:@"TTSPlayerDidEndTimeNotification" object:nil];
    [[BDSSpeechSynthesizer sharedInstance] setApiKey:apiKey withSecretKey:secretKey];
    [[BDSSpeechSynthesizer sharedInstance] setSynthParam:@(BDS_SYNTHESIZER_SPEAKER_MALE_3) forKey:BDS_SYNTHESIZER_PARAM_SPEAKER];
    [[BDSSpeechSynthesizer sharedInstance] setSynthParam:@(6) forKey:BDS_SYNTHESIZER_PARAM_SPEED];
    [[BDSSpeechSynthesizer sharedInstance] cancel];
    [self splitTextWithString:self.currentPageContent];
}

#pragma mark - 点击目录
- (void)didSelectMuluWithChapterIndex:(NSInteger)index {
    [self.muluView dismiss];
    if ([self.delegate respondsToSelector:@selector(audioDidselectChapter:)]) {
        [self.delegate audioDidselectChapter:index];
    }
}

#pragma mark - 按照个数分割字符串 50个字
- (void)splitTextWithString:(NSString *)text {
    if (kStringIsEmpty(text) == NO) {
        [AY_ReadBookTool speakText:text];
//        NSArray *arr = [text componentsSeparatedByString:@"\n"];
//        for (int i =0; i < arr.count; i++) {
//            NSString *str = arr[i];
//            if (str.length >= 60) {
//                NSArray *arr1 = [str componentsSeparatedByString:@"，"];
//                for (int j =0; j < arr1.count; j++) {
//                    [[BDSSpeechSynthesizer sharedInstance] speakSentence:arr1[j] withError:nil];
//                }
//            }else {
//                [[BDSSpeechSynthesizer sharedInstance] speakSentence:arr[i] withError:nil];
//            }
//        }
    }
}

- (void)speechSynthesizer:(AVSpeechSynthesizer *)synthesizer didFinishSpeechUtterance:(AVSpeechUtterance *)utterance {
    if ([AY_ReadBookTool getWorkStatus]) {
        if (self.page >= self.pages.count - 1) {
            if ([self.delegate respondsToSelector:@selector(audioChangeChapter:)]) {
                [self.delegate audioChangeChapter:YES];
            }
        }else {
            self.page = self.page + 1;
            [self.textSlider changePlayProgress:(int)self.page totalLength:(int)self.pages.count];
            if ([self.delegate respondsToSelector:@selector(audioChangePage:)]) {
                [self.delegate audioChangePage:self.page];
            }
    //            [self splitTextWithString:[self p_subGetCurPageContentWithContent:self.content page:self.page pages:self.pages].string];
        }
    }
}

//- (void)speechEnd:(NSNotification *)noti {
//    Log(@"结束");
//    if (self.page >= self.pages.count - 1) {
//        if ([self.delegate respondsToSelector:@selector(audioChangeChapter:)]) {
//            [self.delegate audioChangeChapter:YES];
//        }
//    }else {
//        self.page = self.page + 1;
//        [self.textSlider changePlayProgress:(int)self.page totalLength:(int)self.pages.count];
//        if ([self.delegate respondsToSelector:@selector(audioChangePage:)]) {
//            [self.delegate audioChangePage:self.page];
//        }
//        [self splitTextWithString:[self p_subGetCurPageContentWithContent:self.content page:self.page pages:self.pages].string];
//    }
//}

-(NSAttributedString *)p_subGetCurPageContentWithContent:(NSAttributedString *)conetnt page:(NSInteger)page pages:(NSArray *)pages
{
    NSInteger index = page;
    if (index < 0) {
        index = 0;
    }
    if (index >= pages.count) {
        index = pages.count - 1;
    }
    NSInteger loc = [pages[index] integerValue];
    NSInteger len = 0;
    if (index<pages.count-1) {
        len = [pages[index+1] integerValue] - loc;
    }
    else{
        len = conetnt.length - loc;
    }
    return [conetnt attributedSubstringFromRange:NSMakeRange(loc, len)];
    
}

- (void)setUI {
    self.toolArrays = @[@"AY_audiao_mulu", @"AY_audiao_last", @"AY_audiao_pause", @"AY_audiao_next"];
    self.backImage = [AYTool createImageViewWithFrame:CGRectMake(0, 0, SCREEN_W, SCREEN_H) andImage:nil andBg:nil andRadius:0 andAddSubView:self.view];
    UIBlurEffect *blurEffect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleDark];
    // 毛玻璃视图
    self.effectView = [[UIVisualEffectView alloc] initWithEffect:blurEffect];
    //添加到要有毛玻璃特效的控件中
    self.effectView.frame = self.backImage.bounds;
    [self.view addSubview:self.effectView];
    
    UIButton *leftBtn = [AYTool createButtonWithFrame:CGRectZero andTitle:nil andFont:nil andTitleColor:nil andBg:nil andImage:nil andBgImage:YImage(@"AY_nav_pop_down") andTarget:self andAction:@selector(popVC) andRadius:0 andAddSubView:self.effectView.contentView];
    [leftBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view).offset(YNUM(15));
        make.top.equalTo(self.view).offset(GK_STATUSBAR_HEIGHT + YNUM(20));
        make.width.height.mas_equalTo(YNUM(20));
    }];
    
    UIButton *cancelBtn = [AYTool createButtonWithFrame:CGRectZero andTitle:@"  退出听书" andFont:YFont(14) andTitleColor:[UIColor whiteColor] andBg:nil andImage:YImage(@"AY_read_cancel") andBgImage:nil andTarget:self andAction:@selector(cancelReading) andRadius:0 andAddSubView:self.effectView.contentView];
    [cancelBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.view).offset(-YNUM(15));
        make.top.equalTo(self.view).offset(GK_STATUSBAR_HEIGHT + YNUM(20));
    }];
    
    self.bookImage = [AYTool createImageViewWithFrame:CGRectZero andImage:nil andBg:nil andRadius:YNUM(8) andAddSubView:self.effectView.contentView];
    [self.bookImage mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view);
        make.top.equalTo(self.view).offset(YNUM(20) + GK_STATUSBAR_NAVBAR_HEIGHT);
        make.width.mas_equalTo(YNUM(97));
        make.height.mas_equalTo(YNUM(130));
    }];
    
    self.bookName = [AYTool createLabelWithFrame:CGRectZero andText:nil andTextColor:[UIColor whiteColor] andBgColor:nil andFont:[UIFont boldSystemFontOfSize:YNUM(18)] andLines:1 andRadius:0 andAddSubView:self.effectView.contentView];
    self.bookName.textAlignment = NSTextAlignmentCenter;
    [self.bookName mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.bookImage.mas_bottom).offset(YNUM(20));
        make.left.equalTo(self.view).offset(YNUM(30));
        make.right.equalTo(self.view).offset(-YNUM(30));
    }];
    
    self.bookChapter = [AYTool createLabelWithFrame:CGRectZero andText:nil andTextColor:[UIColor whiteColor] andBgColor:nil andFont:[UIFont boldSystemFontOfSize:YNUM(12)] andLines:1 andRadius:0 andAddSubView:self.effectView.contentView];
    self.bookChapter.textAlignment = NSTextAlignmentCenter;
    [self.bookChapter mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.bookName.mas_bottom).offset(YNUM(10));
        make.left.equalTo(self.view).offset(YNUM(30));
        make.right.equalTo(self.view).offset(-YNUM(30));
    }];
    
    [self.view layoutIfNeeded];
    self.textSlider = [AY_AudioProgressView publicAudioPlayProgressView:CGRectMake(YNUM(20), self.bookName.mj_h + self.bookChapter.mj_y + YNUM(50), SCREEN_W - YNUM(40), YNUM(20)) withType:TimeStyle];
    self.textSlider.backgroundColor = [UIColor clearColor];
    self.textSlider.delegate = self;
    [self.effectView.contentView addSubview:self.textSlider];
    
    UIButton *lastButton;
    UIButton *toolBtn;
    for (int i =0; i < self.toolArrays.count; i++) {
        toolBtn = [AYTool createButtonWithFrame:CGRectZero andTitle:nil andFont:nil andTitleColor:nil andBg:nil andImage:nil andBgImage:YImage(self.toolArrays[i]) andTarget:self andAction:@selector(toolAction:) andRadius:0 andAddSubView:self.effectView.contentView];
        [toolBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            if (lastButton) {
                make.left.equalTo(lastButton.mas_right).offset(YNUM(39));
            }else {
                make.left.equalTo(self.view).offset(YNUM(20));
            }
            if (i == 2) {
                make.top.equalTo(self.textSlider.mas_bottom).offset(YNUM(20));
                make.width.height.mas_equalTo(YNUM(60));
            }else {
                make.top.equalTo(self.textSlider.mas_bottom).offset(YNUM(40));
                make.width.height.mas_equalTo(YNUM(30));
            }
        }];
        toolBtn.tag = i + 1;
        lastButton = toolBtn;
    }
    
    self.speedBtn = [AYTool createButtonWithFrame:CGRectZero andTitle:[NSString stringWithFormat:@"%@  >",self.speedArray[[AYMMKV getStringForKey:@"SPEEDINDEX" defaultValue:@"2"].intValue]] andFont:YFont(16) andTitleColor:[UIColor whiteColor] andBg:[[UIColor whiteColor] colorWithAlphaComponent:0.15] andImage:nil andBgImage:nil andTarget:self andAction:@selector(speedAction) andRadius:YNUM(8) andAddSubView:self.effectView.contentView];
    [self.speedBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view).offset(YNUM(20));
        make.top.equalTo(toolBtn.mas_bottom).offset(YNUM(40));
        make.width.mas_equalTo((SCREEN_W - YNUM(60))/2);
        make.height.mas_equalTo(YNUM(46));
    }];
    
    self.yinSeBtn = [AYTool createButtonWithFrame:CGRectZero andTitle:@"从本页开始阅读  >" andFont:YFont(14) andTitleColor:[UIColor whiteColor] andBg:[[UIColor whiteColor] colorWithAlphaComponent:0.15] andImage:nil andBgImage:nil andTarget:self andAction:@selector(startPageRead) andRadius:YNUM(8) andAddSubView:self.effectView.contentView];
    [self.yinSeBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.view).offset(-YNUM(20));
        make.top.width.height.equalTo(self.speedBtn);
    }];
    
    UILabel *tuijian = [AYTool createLabelWithFrame:CGRectZero andText:@"同类型推荐" andTextColor:[UIColor whiteColor] andBgColor:nil andFont:[UIFont boldSystemFontOfSize:YNUM(18)] andLines:1 andRadius:0 andAddSubView:self.effectView.contentView];
    [tuijian mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view).offset(YNUM(20));
        make.top.equalTo(self.yinSeBtn.mas_bottom).offset(YNUM(40));
    }];
    
    UIImageView *changeImage = [AYTool createImageViewWithFrame:CGRectZero andImage:YImage(@"AY_audio_change") andBg:nil andRadius:YNUM(4) andAddSubView:self.effectView.contentView];
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(loadData)];
    [changeImage addGestureRecognizer:tap];
    [changeImage mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(tuijian);
        make.right.equalTo(self.view).offset(YNUM(-20));
        make.height.mas_equalTo(YNUM(13));
        make.width.mas_equalTo(YNUM(13));
    }];
    
    UIButton *changeBtn = [AYTool createButtonWithFrame:CGRectZero andTitle:@"换一换" andFont:YFont(14) andTitleColor:[UIColor whiteColor] andBg:nil andImage:nil andBgImage:nil andTarget:self andAction:@selector(loadData) andRadius:0 andAddSubView:self.effectView.contentView];
    [changeBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(tuijian);
        make.right.equalTo(changeImage.mas_left).offset(YNUM(-3));
        make.height.mas_equalTo(YNUM(26));
    }];
    
    [self.view addSubview:self.collectionView];
    [self.collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.bottom.right.equalTo(self.view);
        make.top.equalTo(tuijian.mas_bottom).offset(20);
    }];
    
    [self setData];
}

- (void)startPageRead {
    if ([AY_ReadBookTool getWorkStatus]) {
        return;
    }
    [AY_ReadBookTool getManager].delegate = self;
    [self splitTextWithString:self.currentPageContent];
}

- (void)cancelReading {
    self.isQuit = YES;
    [AY_ReadBookTool getManager].delegate = nil;
    [AY_ReadBookTool stopSpeak];
//    [[BDSSpeechSynthesizer sharedInstance] cancel];
//    [BDSSpeechSynthesizer releaseInstance];
    if ([self.delegate respondsToSelector:@selector(audioDismiss)]) {
        [self.delegate audioDismiss];
    }
}

#pragma mark -- UICollectionViewDelegate
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return MIN(8, self.dataSource.count);
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    AY_AudioBookCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"AY_AudioBookCell" forIndexPath:indexPath];
    cell.model = self.dataSource[indexPath.row];
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    
    if ([self.delegate respondsToSelector:@selector(pushBookDetailWithBookId:)]) {
        [self.delegate pushBookDetailWithBookId:[self.dataSource[indexPath.row] bookId]];
    }
}

- (void)yinseAction {
    [self showAlertWith:self.yinseArray andType:@"请选择方言"];
}

- (void)speedAction {
    [self showAlertWith:self.speedArray andType:@"请选择语速"];
}

- (void)showAlertWith:(NSArray *)array andType:(NSString *)type {
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"" message:type preferredStyle:UIAlertControllerStyleActionSheet];

    for (int i = 0; i < array.count; i++) {
        UIAlertAction *action = [UIAlertAction actionWithTitle:array[i] style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            if ([type isEqualToString:@"请选择语速"]) {
                [self speedChangeWithIndex:i];
            }else {
                [self yinseChangeWithIndex:i];
            }
        }];
        [alertController addAction:action];
    }
    UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
    }];
    [alertController addAction:action2];
    [self presentViewController:alertController animated:YES completion:nil];
}

- (void)speedChangeWithIndex:(NSInteger)index {
    [AYMMKV setString:[NSString stringWithFormat:@"%lu",index] forKey:SPEEDINDEX];
    [self.speedBtn setTitle:[NSString stringWithFormat:@"%@  >",self.speedArray[index]] forState:UIControlStateNormal];
//    [[BDSSpeechSynthesizer sharedInstance] cancel];
    [AY_ReadBookTool getManager].delegate = nil;
    [AY_ReadBookTool stopSpeak];
//    [[BDSSpeechSynthesizer sharedInstance] setSynthParam:@(index+3) forKey:BDS_SYNTHESIZER_PARAM_SPEED];
    [self splitTextWithString:self.currentPageContent];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(5.0 * NSEC_PER_SEC)), dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        [AY_ReadBookTool getManager].delegate = self;
    });
}

- (void)yinseChangeWithIndex:(NSInteger)index {
    [self.yinSeBtn setTitle:[NSString stringWithFormat:@"%@  >",self.yinseArray[index]] forState:UIControlStateNormal];
//    [[BDSSpeechSynthesizer sharedInstance] cancel];
    [AY_ReadBookTool getManager].delegate = nil;
    [AY_ReadBookTool stopSpeak];
    [AY_ReadBookTool setYinSe:index];
//    [[BDSSpeechSynthesizer sharedInstance] setSynthParam:@(index) forKey:BDS_SYNTHESIZER_PARAM_SPEAKER];
    [self splitTextWithString:self.currentPageContent];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(5.0 * NSEC_PER_SEC)), dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        [AY_ReadBookTool getManager].delegate = self;
    });
}

- (void)toolAction:(UIButton *)btn {
    if (btn.tag == 2) {
        if ([self getTimer] - self.timeNum<=250) {
            NSLog(@"时间间隔===%ld",[self getTimer] - self.timeNum);
            return;
        }
        self.timeNum = [self getTimer];
        if (self.page == 0) {
            if ([self.delegate respondsToSelector:@selector(audioChangeChapter:)]) {
                [self.delegate audioChangeChapter:NO];
            }
            return;
        }
        self.page = self.page - 1;
        [self.textSlider changePlayProgress:(int)self.page totalLength:(int)self.pages.count];
//        [[BDSSpeechSynthesizer sharedInstance] cancel];
//        [AY_ReadBookTool getManager].delegate = nil;
//        [AY_ReadBookTool stopSpeak];
        if ([self.delegate respondsToSelector:@selector(audioChangePage:)]) {
            [self.delegate audioChangePage:self.page];
        }
//        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
//            [self splitTextWithString:[self p_subGetCurPageContentWithContent:self.content page:self.page pages:self.pages].string];
////            [AY_ReadBookTool getManager].delegate = self;
//        });
//        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(10.0 * NSEC_PER_SEC)), dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
//            [AY_ReadBookTool getManager].delegate = self;
//        });
    }else if (btn.tag == 4) {
        if ([self getTimer] - self.timeNum<=250) {
            NSLog(@"时间间隔===%ld",[self getTimer] - self.timeNum);
            return;
        }
        self.timeNum = [self getTimer];
        if (self.page == self.pages.count - 1) {
            if ([self.delegate respondsToSelector:@selector(audioChangeChapter:)]) {
                [self.delegate audioChangeChapter:YES];
            }
            return;
        }
        self.page = self.page + 1;
        [self.textSlider changePlayProgress:(int)self.page totalLength:(int)self.pages.count];
//        [[BDSSpeechSynthesizer sharedInstance] cancel];
//        [AY_ReadBookTool getManager].delegate = nil;
//        [AY_ReadBookTool stopSpeak];
        if ([self.delegate respondsToSelector:@selector(audioChangePage:)]) {
            [self.delegate audioChangePage:self.page];
        }
//        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
//            [self splitTextWithString:[self p_subGetCurPageContentWithContent:self.content page:self.page pages:self.pages].string];
////            [AY_ReadBookTool getManager].delegate = self;
//        });
//        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(10.0 * NSEC_PER_SEC)), dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
//            [AY_ReadBookTool getManager].delegate = self;
//        });
    }else if (btn.tag == 1) {
        [self handleMuluAction];
    }else if (btn.tag == 3) {
        if (![AY_ReadBookTool getManager].isPaused) {
            [AY_ReadBookTool pauseSpeak];
            [btn setBackgroundImage:YImage(@"AY_audiao_play") forState:UIControlStateNormal];
        }else {
            [AY_ReadBookTool continueSpeak];
            [btn setBackgroundImage:YImage(@"AY_audiao_pause") forState:UIControlStateNormal];
        }
//        if ([BDSSpeechSynthesizer sharedInstance].synthesizerStatus == BDS_SYNTHESIZER_STATUS_WORKING) {
//            [[BDSSpeechSynthesizer sharedInstance] pause];
//            [btn setBackgroundImage:YImage(@"AY_audiao_play") forState:UIControlStateNormal];
//        }else {
//            [[BDSSpeechSynthesizer sharedInstance] resume];
//            [btn setBackgroundImage:YImage(@"AY_audiao_pause") forState:UIControlStateNormal];
//        }
    }
}

- (void)handleMuluAction {
    if(kStringIsEmpty(self.bookModel.bookId)) {
        ShowToast(@"暂无目录");
        return;
    }
    [AYApiRequest getBookChapterListWithPageNum:@"1" andPageSize:@"10000" andArticleId:self.bookModel.bookId Success:^(AY_ChapterModel * _Nonnull pkg) {
        if([pkg.code isEqualToString:@"200"]) {
            [self navTopDirectoryPage:pkg.rows];
        }
    } failure:^(int status, NSString * _Nonnull info) {
        ShowToast(@"亲，网络不顺畅哟~");
    }];
}

- (void)navTopDirectoryPage:(NSArray *)dataAry {
    if (self.muluView.superview) {
        [self.muluView dismiss];
    }else {
        //隐藏=YES,显示=NO; Animation:动画效果
        [[UIApplication sharedApplication] setStatusBarHidden:NO withAnimation:UIStatusBarAnimationSlide];
        [self setNeedsStatusBarAppearanceUpdate];
        self.muluView = [[AY_AudioMuLuView alloc] init];
        self.muluView.dataSource = dataAry;
        self.muluView.delegate = self;
        [self.muluView showMuLuView:self.view];
    }
}

//MARK:-------------改变播放进度
- (void)changePlayTimeByPublicAudioPlayProgressView:(int)playCount
{
    [self.textSlider changePlayProgress:playCount totalLength:100];
}

// 拖动结束
- (void)changePlayTimeByPublicAudioPlayProgressViewEnd:(int)playCount
{
    NSLog(@"====================================移动结束%d",playCount);
    [self.textSlider changePlayProgress:playCount totalLength:100];
    
}

- (void)popVC {
    if ([self.delegate respondsToSelector:@selector(audioDismiss)]) {
        [self.delegate audioDismiss];
    }
}

- (void)setBookModel:(BookModel *)bookModel {
    _bookModel = bookModel;
    [self setUI];
    [self loadData];
}

- (void)setData {
    [self.bookImage sd_setImageWithURL:[NSURL URLWithString:self.bookModel.coverImg] placeholderImage:YImage(@"placeholderImage")];
    [self.backImage sd_setImageWithURL:[NSURL URLWithString:self.bookModel.coverImg] placeholderImage:YImage(@"placeholderImage")];
    self.bookName.text = self.bookModel.title;
}

- (long long)getTimer
{
    double timms = [[NSDate date] timeIntervalSince1970]*1000;
    long long timmsInt = [[NSString stringWithFormat:@"%f",timms] longLongValue];
    return timmsInt;
}

- (UICollectionView *)collectionView {
    if (!_collectionView) {
        UICollectionViewFlowLayout * layout = [[UICollectionViewFlowLayout alloc]init];
        layout.itemSize = CGSizeMake((SCREEN_W - YNUM(85))/4, YNUM(120));
        layout.scrollDirection = UICollectionViewScrollDirectionVertical;
        layout.sectionInset = UIEdgeInsetsMake(0, 15, 0, 15);
        layout.minimumLineSpacing = 0;
        layout.minimumInteritemSpacing = 0;
        _collectionView = [[UICollectionView alloc]initWithFrame:CGRectZero collectionViewLayout:layout];
        _collectionView.dataSource = self;
        _collectionView.scrollEnabled = NO;
//        _collectionView.contentInset = UIEdgeInsetsMake(10, 0, 0, 0);
        _collectionView.showsVerticalScrollIndicator = NO;
        _collectionView.backgroundColor = [UIColor clearColor];
        _collectionView.delegate = self;
        [_collectionView registerClass:[AY_AudioBookCell class] forCellWithReuseIdentifier:@"AY_AudioBookCell"];
        [_collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"footer"];
    }
    return _collectionView;
}

- (NSMutableArray *)dataSource {
    if (!_dataSource) {
        _dataSource = [NSMutableArray array];
    }
    return _dataSource;
}

- (void)dealloc {
    
}
@end
